// pages/order/orderedStatus/orderedStatus.js
const handler = require("../../../utils/function.js");
var app = getApp(),
  api = require("../../../api.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showTime: true, //是否开始行程
    isWait: false, //是否开始行程
    img: handler.driverImg,
    driver: {},
    order: {},
    markers: [],
    polyline: [{
      points: [{
        longitude: wx.getStorageSync("startAddress").longitude,
        latitude: wx.getStorageSync("startAddress").latitude
      }, {
        longitude: 108.94,
        latitude: wx.getStorageSync("startAddress").latitude
      }],
      color: "#0299de",
      width: 9,
      dottedLine: false,
      arrowLine: true,
    }],
    controls: [{
      id: 1,
      iconPath: '../../../images/user/icon-22.png',
      position: {
        left: 10,
        top: 10,
        width: 50,
        height: 50
      },
      clickable: true
    }],
    user_address: [{
      lat: null,
      lng: null
    }],
    longitude: null,
    latitude: null,
    ordernum: 0, //累计使用代驾次数
    tiqiankaishi: "0",
  },
  // 到达用户位置
  arriveGoal: function(e) {
    var that = this,
      order_no = that.data.order_no;
     
    wx.getLocation({
      type: 'gcj02',
      success: function (rs) {
        app.request({
          url: api.user.driverToStart,
          method: 'post',
          data: {
            order_no: order_no,
            lat: rs.latitude,
            lng: rs.longitude
          },
          success: function (res) {
            if (res.code == 1) {
              that.getorder();
              app.waitTime();
              that.waitTimeCount();
              app.endReportHeart();
            }
          }
        })
      }
    })

    // wx.showModal({
    //   title: '提示',
    //   content: '确认您已到达客户身边？',
    //   success: function(res) {
    //     if (res.confirm) {
    //       // 发起请求结束上报位置
    //       wx.getLocation({
    //         type: 'gcj02',
    //         success: function (rs) {
    //           app.request({
    //             url: api.user.driverToStart,
    //             method: 'post',
    //             data: {
    //               order_no: order_no,
    //               lat: rs.latitude,
    //               lng: rs.longitude
    //             },
    //             success: function (res) {
    //               if (res.code == 1) {
    //                 that.getorder();
    //                 app.waitTime();
    //                 that.waitTimeCount();
    //                 app.endReportHeart();
    //               }
    //             }
    //           })
    //         }
    //       })
    //     } else {
    //       // 测试  最终要删
    //       app.endWaitTime();
    //       clearInterval(that.timer);
    //     }
    //   }
    // })

  },
  // 司机等待时长显示
  waitTimeCount() {
    let time = wx.getStorageSync('timeWait') || 1;
    this.timer = setInterval(() => {
      this.formatSeconds(time++);
    }, 1000);

  },
  onHide () {
    console.log("清除定时器");
    clearInterval(this.timer);
  },
  // 修改时间格式
  formatSeconds(value) {
    var theTime = parseInt(value); // 秒
    var middle = 0; // 分
    var hour = 0; // 小时

    if (theTime > 60) {
      middle = parseInt(theTime / 60);
      theTime = parseInt(theTime % 60);
      if (middle > 60) {
        hour = parseInt(middle / 60);
        middle = parseInt(middle % 60);
      }
    }
    var result = "" + parseInt(theTime) + "秒";
    if (middle > 0) {
      result = "" + parseInt(middle) + "分" + result;
    }
    if (hour > 0) {
      result = "" + parseInt(hour) + "小时" + result;
    }
    this.setData({
      time: result
    });
  },
  // 获取当前经纬度
  get_lat_lng: function(callback) {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        console.log(res, '22222222222222')
        var latitude = res.latitude
        var longitude = res.longitude
        var params = latitude + "," + longitude;
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1', //根据经纬度转换成具体地址
          data: {
            "key": "EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD",
            "location": params
          },
          method: 'GET',
          success(rs) {
            console.log(rs)
            that.setData({
              now_location: rs.data.result
            })
            callback({
              now_location: rs.data.result.address,
              latitude: latitude,
              longitude: longitude
            })
          }
        })
      },
    })
  },
  // 判断是否开启后端定位权限
  openUserLocationBackground(e) {
    let that = this;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocationBackground']) {
          wx.openSetting({});
          that.startStep(e);

          // wx.showModal({
          //   title: '提示',
          //   content: '此功能需要后台运行,确定打开后台运行权限?',
          //   success: function(res) {
          //     if (res.confirm) {
          //       wx.openSetting({});
          //       that.startStep(e);
          //       return true;
          //     } else {
          //       return false
          //     }
          //   }
          // })
        } else {
          that.startStep(e);
        }
      }
    })
  },
  // 开始行程方法
  startStep(e) {
    // 开始形成获取当前位置
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        console.log(res, 'dsadaslkdhjl;asknd;lkasmnd;lkasmd;lkasmd;lkasnd;lknas')
        const latitude = res.latitude
        const longitude = res.longitude
        app.driver_position[0].latitude = latitude
        app.driver_position[0].longitude = longitude
      }
    })
    var that = this;
    var tiqiankaishi = this.data.tiqiankaishi;
    var formid = e.detail.formId;
    
    let order = this.data.order;
    this.get_lat_lng((res) => {
      let start_point = res.now_location;
      let latitude = res.latitude;
      let longitude = res.longitude;
      if (this.data.tiqiankaishi == "1") {
        wx.showModal({
          title: '提示',
          content: '该订单未到出发时间,请联系客户确认时间',
          success: function(res) {
            if (res.confirm) {
              let order = that.data.order;
              app.request({
                url: api.order.ordering,
                method: 'post',
                data: {
                  start_point: start_point,
                  latitude: latitude,
                  longitude: longitude,
                  formid: formid,
                  order_no: e.currentTarget.dataset.order_no,
                },
                success: function(rs) {
                  if (rs.code == 1) {
                    if(order.driverid != order.uid) {
                      app.gateway(e.currentTarget.dataset.order_no, 2)
                    }
                    wx.redirectTo({
                      url: e.currentTarget.dataset.skip
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: rs.msg,
                      success: function() {
                        wx.navigateBack({
                          delta: 1
                        })
                      }
                    })
                  }
                }
              })
            }
          }
        })
        return
      }
      app.request({
        url: api.order.ordering,
        method: 'post',
        data: {
          formid: formid,
          start_point: start_point,
          latitude: latitude,
          longitude: longitude,
          order_no: e.currentTarget.dataset.order_no,
        },
        success: function(rs) {
          if (rs.code == 1) {
            if(order.driverid != order.uid) {
              app.gateway(e.currentTarget.dataset.order_no, 2)
            }
            wx.redirectTo({
              url: e.currentTarget.dataset.skip
            })
          } else {
            wx.showModal({
              title: '提示',
              content: rs.msg,
              success: function() {
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          }
        }
      })
    })
  },
  startTime() {
    wx.startLocationUpdateBackground({
      success(res) {
        var i = 0;
        wx.onLocationChange(function(rese) {
          console.log("开始监听");
          i++;
          if (i % 5 == 0) {
            app.Request({
              url: 'real_time/add',
              method: 'post',
              data: {
                lat: rese.latitude,
                lng: rese.longitude
              },
            }).then((res) => {
              // if (res.code == 1) {

              // } else {

              // }
            })
          }
        })
      }
    })
  },
  intoPageHandler: function(e) {
    var that = this;
    app.endWaitTime();
    that.openUserLocationBackground(e)
    // wx.showModal({
    //   title: '提示',
    //   content: '确认乘客已接到并开始行程？',
    //   success: function(res) {
    //     if (!res.confirm) {
    //       return false;
    //     } else {
    //       app.endWaitTime();
    //       that.openUserLocationBackground(e)
    //     }
    //   }
    // })
  },
  // callPhoneHandler 打电话
  callPhoneHandler: function(e) {
    handler.callPhoneHandler(e.currentTarget.dataset.phone);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("页面数据", options);
    if (options.orderstart) {
      this.setData({
        showTime: false
      })
    }
    this.setData({
      order_no: options.order_no,
    })
    // 获取优惠券
    if (options.uid) {
      app.shareCouponsMessage(options.uid)
    }
  },
  getPolyline: function(slocaltion) {
    const that = this;
    const {
      polyline
    } = this.data;
    const froms = slocaltion[1].latitude + "," + slocaltion[1].longitude + "&to=" + slocaltion[0].latitude + "," + slocaltion[0].longitude;
    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${froms}&key=EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD`,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res);
        if (res.data.status === 384) {} else {
          var coors = res.data.result.routes[0].polyline;
          for (var i = 2; i < coors.length; i++) {
            coors[i] = coors[i - 2] + coors[i] / 1000000
          }
          const points = [];
          for (var j = 0; j < coors.length; j += 2) {
            points[points.length] = {
              longitude: coors[j + 1],
              latitude: coors[j]
            }
          }
          polyline[0].points = points;
          that.setData({
            polyline: polyline
          })
        }
      },
      fail: function() {
        // showToast('网络出现错误', "none")
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getorder();
    if (wx.getStorageSync('timeWait')) {
      this.waitTimeCount();
    }
  },
  // 获取订单信息
  getorder: function() {
    var that = this;
    app.request({
      url: api.order.getfind,
      method: 'post',
      data: {
        order_no: that.data.order_no,
      },
      success: function(rs) {

        wx.hideLoading()
        that.setData({
          order: rs.data,
          markers: rs.data.slocaltion,
          driver: wx.getStorageSync("driver"),
          longitude: rs.data.elocaltion.lng,
          latitude: rs.data.elocaltion.lat,
          ordernum: rs.data.ordernum,
          elocation: rs.data.elocaltion,
          slocation: rs.data.slocation.location,
          isWait: rs.data.is_service == 4 ? true : false
        })
        that.getPolyline(rs.data.slocaltion);
        wx.setStorageSync("server_phone", rs.data.passenger_phone);
        wx.setStorageSync("ordernum", rs.data.ordernum);
        // 弹出提示信息
        /**
         * is_out 0 到达 1 未到
         * 
         * 
         */
        if (rs.data.is_out == 1) {
          that.setData({
            tiqiankaishi: '1'
          })
        }
      }
    })
    this.setData({
      //order: wx.getStorageSync("current_order"),
    });
    // 修改地图高
    this.changeMapHeight()
  },
  // 预约订单客户确认
  is_going: function() {
    let that = this;
    app.request({
      url: api.order_branch.setout,
      method: 'post',
      data: {
        order_no: that.data.order_no,
      },
      success: function(rs) {

      }
    })
  },
  // 修改地图高
  changeMapHeight: function() {
    let that = this;
    wx.getSystemInfo({
      success: function success(res) {
        var controlsH = res.windowWidth / 750 * 440; //计算一像素的宽度 res.windowWidth
        var map_height = res.windowHeight - controlsH;
        var controls = [{
          id: 1,
          iconPath: '../../../images/driver/icon-50.png',
          position: {
            left: 10,
            top: map_height - 56,
            width: 50,
            height: 50
          },
          clickable: true
        }, {
          id: 2,
          iconPath: '../../../images/driver/start.png',
          position: {
            left: 10,
            top: map_height - 110,
            width: 50,
            height: 50
          },
          clickable: true
        }, {
          id: 3,
          iconPath: '../../../images/driver/cancel.png',
          position: {
            left: 10,
            top: map_height - 164,
            width: 50,
            height: 50
          },
          clickable: true
        }];
        // , {
        //   id: 4,
        //     iconPath: '../../../images/driver/timelength.png',
        //       position: {
        //     left: 10,
        //       top: map_height - 218,
        //         width: 50,
        //           height: 50
        //   },
        //   clickable: true
        // }
        that.setData({
          winPath: {
            w: res.windowWidth,
            h: res.windowHeight
          },
          map_height,
          controls: controls
        });
      }
    });
  },
  controltap: function(e) {
    if (e.controlId == 1) {
      this.getAddress()
      return
    }
    if (e.controlId == 2) {
      this.startHandler()
      return
    }
    if (e.controlId == 3) {
      this.cancleOrder()
      return
    }
    if (e.controlId == 4) {
      this.timelength()
      return
    }
  },
  // 开始时长计费
  timelength() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定开始时长计费？',
      success: function(res) {
        if (res.confirm) {
          app.request({
            url: api.order.arrive,
            method: 'post',
            data: {
              order_no: that.data.order.order_no,
            },
            success: function(res) {
              if (res.code == 1) {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                })
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                })
              }
            }
          })
        }
      }
    })

  },
  // 取消订单
  cancleOrder: function() {
    var order_no = this.data.order.order_no
    wx.navigateTo({
      url: '/pages/driver/deleteOrderMasker/index?order_no=' + order_no,
    })
  },
  // 获取当前位置
  getAddress: function() {
    let that = this;
    wx.getLocation({
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
      },
    })
  },
  // 跳转起点
  startHandler: function() {
    var that = this;
    let slocation = this.data.slocation;
    if (slocation.lat && slocation.lng) {
      wx.openLocation({
        latitude: slocation.lat,
        longitude: slocation.lng,
        name: that.data.order.start_adds
      })
    }
  },
})